<template>
    <div class="callback-page">
        <div class="callback-card">
            <div class="status-content">
                <!-- 处理中状态 -->
                <div v-if="processing" class="processing-state">
                    <el-icon class="loading-icon" size="48">
                        <Loading />
                    </el-icon>
                    <h3>正在处理钉钉登录...</h3>
                    <p class="subtitle">请稍候，我们正在验证您的身份</p>
                </div>

                <!-- 成功状态 -->
                <div v-else-if="success" class="success-state">
                    <el-icon class="success-icon" size="48" color="#67c23a">
                        <SuccessFilled />
                    </el-icon>
                    <h3>登录成功！</h3>
                    <p class="subtitle">欢迎回来，{{ userInfo.name || '用户' }}</p>
                    <p class="redirect-info">{{ countdown }}秒后自动跳转到首页...</p>
                    <el-button type="primary" @click="goToHome">
                        立即进入
                    </el-button>
                </div>

                <!-- 错误状态 -->
                <div v-else-if="error" class="error-state">
                    <el-icon class="error-icon" size="48" color="#f56c6c">
                        <Warning />
                    </el-icon>
                    <h3>登录失败</h3>
                    <p class="error-message">{{ errorMessage }}</p>
                    <div class="action-buttons">
                        <el-button @click="retryLogin">重试</el-button>
                        <el-button type="primary" @click="goToLogin">返回登录</el-button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Loading, SuccessFilled, Warning } from '@element-plus/icons-vue'
import request from '@/utils/request'

const router = useRouter()
const route = useRoute()

// 状态管理
const processing = ref(true)
const success = ref(false)
const error = ref(false)
const errorMessage = ref('')
const userInfo = ref({})
const countdown = ref(3)

let countdownTimer = null

onMounted(() => {
    handleDingTalkCallback()
})

onUnmounted(() => {
    if (countdownTimer) {
        clearInterval(countdownTimer)
    }
})

async function handleDingTalkCallback() {
    try {
        // 获取URL中的授权码
        const authCode = route.query.code
        const state = route.query.state
        
        console.log('钉钉回调参数:', { authCode, state, query: route.query })
        
        if (!authCode) {
            throw new Error('未获取到钉钉授权码，请重新登录')
        }

        // 模拟处理时间，让用户看到处理过程
        await new Promise(resolve => setTimeout(resolve, 1000))

        // 调用后端接口处理钉钉登录
        const response = await request.post('/Login/ding/callback', {
            code: authCode,
            state: state
        })

        console.log('钉钉登录响应:', response.data)

        if (response.data && response.data.code === 0) {
            const { token, user } = response.data.data
            
            // 存储token到localStorage
            localStorage.setItem('token', token)
            
            // 设置用户信息
            userInfo.value = user
            
            // 显示成功状态
            processing.value = false
            success.value = true
            
            // 开始倒计时
            startCountdown()
            
            ElMessage.success('钉钉登录成功！')
        } else {
            throw new Error(response.data?.msg || '登录失败')
        }
        
    } catch (err) {
        console.error('钉钉登录回调处理失败:', err)
        processing.value = false
        error.value = true
        errorMessage.value = err.response?.data?.msg || err.message || '登录过程中发生错误，请重试'
        ElMessage.error(errorMessage.value)
    }
}

function startCountdown() {
    countdownTimer = setInterval(() => {
        countdown.value--
        if (countdown.value <= 0) {
            clearInterval(countdownTimer)
            goToHome()
        }
    }, 1000)
}

function goToHome() {
    router.replace('/home') // 使用replace避免返回到回调页面
}

function goToLogin() {
    router.replace('/') // 使用replace避免返回到回调页面
}

function retryLogin() {
    // 重新发起钉钉登录
    goToLogin()
}
</script>

<style scoped>
.callback-page {
    min-height: 100vh;
    display: flex;
    align-items: center;
    justify-content: center;
    background: linear-gradient(135deg, #f5f7fa 0%, #e6ecf5 100%);
    padding: 24px;
}

.callback-card {
    width: 420px;
    background: #fff;
    border-radius: 16px;
    box-shadow: 0 12px 30px rgba(0, 0, 0, 0.08);
    padding: 48px 32px;
    text-align: center;
}

.status-content {
    display: flex;
    flex-direction: column;
    align-items: center;
}

/* 处理中状态样式 */
.processing-state {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 16px;
}

.loading-icon {
    animation: spin 1s linear infinite;
    color: #1677ff;
}

@keyframes spin {
    0% { transform: rotate(0deg); }
    100% { transform: rotate(360deg); }
}

/* 成功状态样式 */
.success-state {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 12px;
}

.success-icon {
    animation: bounce 0.6s ease-in-out;
}

@keyframes bounce {
    0%, 100% { transform: scale(1); }
    50% { transform: scale(1.1); }
}

.redirect-info {
    color: #909399;
    font-size: 13px;
    margin: 8px 0;
}

/* 错误状态样式 */
.error-state {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 16px;
}

.error-icon {
    animation: shake 0.5s ease-in-out;
}

@keyframes shake {
    0%, 100% { transform: translateX(0); }
    25% { transform: translateX(-5px); }
    75% { transform: translateX(5px); }
}

.action-buttons {
    display: flex;
    gap: 12px;
    margin-top: 8px;
}

/* 通用样式 */
h3 {
    margin: 0;
    font-size: 20px;
    font-weight: 600;
    color: #333;
}

.subtitle {
    margin: 0;
    color: #666;
    font-size: 14px;
    line-height: 1.5;
}

.error-message {
    color: #f56c6c;
    font-size: 14px;
    margin: 0;
    line-height: 1.5;
    max-width: 300px;
}

.el-button {
    margin-top: 4px;
    padding: 10px 20px;
}
</style> 